<?php
// +----------------------------------------------------------------------
// | duoduojie app system
// +----------------------------------------------------------------------
// | Copyright (c) 2017 duoduojie app All rights reserved.
// +----------------------------------------------------------------------
// | Author: Gooe <zqscjj@163.com> QQ:81009953
// +----------------------------------------------------------------------
namespace Ddj;
use MultiHttp\MultiRequest;
use MultiHttp\Response;
/**
 * 淘宝联盟接口
 * @author zqs
 */
include env('extend_path').'/taobao/TopSdk.php';
class Tk
{
    public $options;
    /**
     * 初始化
     */
    public function __construct($options=[])
    {
        //公共参数,可被覆盖
        $db_config = get_db_config(true);
        $this->options['appkey']        = $db_config['tk_cfg']['taobao']['appkey'];
        $this->options['appsecret']     = $db_config['tk_cfg']['taobao']['appsecret'];
        $this->options['pid']           = $db_config['tk_cfg']['taobao']['pid'];
        $this->options['big_appkey']    = $db_config['tk_cfg']['taobao']['big_appkey'];
        $this->options['big_appsecret'] = $db_config['tk_cfg']['taobao']['big_appsecret'];
        if ($options){
            $this->options = array_merge($this->options,$options);
        }
        $pid_arr = str2arr($this->options['pid'],'_');
        $this->options['siteid'] = $pid_arr[2];
        $this->options['adzoneid'] = $pid_arr['3'];
    }
    /**
     * 废弃
     * 优惠券查询接口 好券清单API【导购】
     */
    public function conpou(){
        $c = new \TopClient();
        $c->appkey = $this->options['appkey'];
        $c->secretKey = $this->options['appsecret'];
        $req = new \TbkDgItemCouponGetRequest();
        $req->setAdzoneId($this->options['adzoneid']);
        //1：PC，2：无线，默认：2
        $platform = isset($this->options['platform']) ? $this->options['platform'] : 2;
        $req->setPlatform($platform);
        //后台类目ID，用,分割，最大10个，该ID可以通过taobao.itemcats.get接口获取到
        if (isset($this->options['cat'])) $req->setCat($this->options['cat']);
        //页大小，默认20，1~100
        if (isset($this->options['page_size'])) $req->setPageSize($this->options['page_size']);
        //查询词
        if (isset($this->options['q'])) $req->setQ($this->options['q']);
        //第几页，默认：1（当后台类目和查询词均不指定的时候，最多出10000个结果，即page_no*page_size不能超过200；当指定类目或关键词的时候，则最多出100个结果）
        if (isset($this->options['page_no'])) $req->setPageNo($this->options['page_no']);
        //是滞过滤佣金
        $filter = isset($this->options['filter']) ?$this->options['filter'] : false ;
        
        $resp = $c->execute($req);
        $resp = json_decode(json_encode($resp),true);//return $resp;
        $coupon_list = $resp['results']['tbk_coupon'];
        if ($coupon_list){
            if (!is_array($coupon_list[0])){
                $resp['results']['tbk_coupon'] = [];
                $resp['results']['tbk_coupon'][] = $coupon_list;
            }
            foreach ($resp['results']['tbk_coupon'] as $k=>$v){
                //删除失效的
                if (!isset($v['coupon_info'])){
                    unset($resp['results']['tbk_coupon'][$k]);
                }else {
                    $resp['results']['tbk_coupon'][$k]['coupon_price'] = get_coupon_price($v['coupon_info']);//优惠券面额
                    $resp['results']['tbk_coupon'][$k]['after_coupon_price'] = round($v['zk_final_price'] - get_coupon_price($v['coupon_info']),2);//券后价
                }
                
                //过滤
                if ($filter > 0){
                    if ($v['commission_rate'] <= $filter)
                        unset($resp['results']['tbk_coupon'][$k]);
                }
            }
        }
        return $resp;
    }
    /** 废弃
     * 淘宝客商品查询
     */
    public function item_get()
    {
        $c = new \TopClient();;
        $c->appkey = $this->options['appkey'];
        $c->secretKey = $this->options['appsecret'];
        $req = new \TbkItemGetRequest();
        $req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
        //查询词
        if (isset($this->options['q'])) $req->setQ($this->options['q']);
        //后台类目ID，用,分割，最大10个，该ID可以通过taobao.itemcats.get接口获取到
        if (isset($this->options['cat'])) $req->setCat($this->options['cat']);
        //所在地
        if (isset($this->options['itemloc'])) $req->setItemloc($this->options['itemloc']);
        //排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi）
        if (isset($this->options['sort']))  $req->setSort($this->options['sort']);
        //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
        if (isset($this->options['is_tmall'])) $req->setIsTmall($this->options['is_tmall']);
        //是否海外商品，设置为true表示该商品是属于海外商品，设置为false或不设置表示不判断这个属性
        if (isset($this->options['is_overseas'])) $req->setIsOverseas($this->options['is_overseas']);
        //折扣价范围下限，单位：元
        if (isset($this->options['start_price'])) $req->setStartPrice($this->options['start_price']);
        //折扣价范围上限，单位：元
        if (isset($this->options['end_price'])) $req->setEndPrice($this->options['end_price']);
        //淘客佣金比率上限，如：1234表示12.34%
        if (isset($this->options['start_tk_rate'])) $req->setStartTkRate($this->options['start_tk_rate']);
        //淘客佣金比率下限，如：1234表示12.34%
        if (isset($this->options['end_tk_rate'])) $req->setEndTkRate($this->options['end_tk_rate']);
        //链接形式：1：PC，2：无线，默认：１
        $platform = isset($this->options['platform']) ? $this->options['platform'] : "2";
        $req->setPlatform($platform);
        //页大小，默认20，1~100
        if (isset($this->options['page_size'])) $req->setPageSize($this->options['page_size']);
        //第几页，默认：1（当后台类目和查询词均不指定的时候，最多出10000个结果，即page_no*page_size不能超过200；当指定类目或关键词的时候，则最多出100个结果）
        if (isset($this->options['page_no'])) $req->setPageNo($this->options['page_no']);
        //是滞过滤佣金 手动过滤TODO
        $filter = isset($this->options['filter']) ?$this->options['filter'] : false ;
        
        $resp = $c->execute($req);
        $resp = json_decode(json_encode($resp),true);
        if ($resp['total_results']>0){
            if (!is_array($resp['results']['n_tbk_item'][0])){
                $temp_n_tbk_item = $resp['results']['n_tbk_item'];
                $resp['results']['n_tbk_item'] = [];
                $resp['results']['n_tbk_item'][] = $temp_n_tbk_item;
            }
            /* foreach ($resp['results']['n_tbk_item'] as $k=>$v){
                $gaoyonog = self::gaoyong($v['num_iid']);
                if (!$gaoyonog){
                    unset($resp['results']['n_tbk_item'][$k]);//查不到高佣信息直接删除
                }else {
                    $resp['results']['n_tbk_item'][$k] = array_merge($resp['results']['n_tbk_item'][$k],$gaoyonog);
                    if (isset($gaoyonog['coupon_info'])){
                        $resp['results']['n_tbk_item'][$k]['coupon_price'] = get_coupon_price($gaoyonog['coupon_info']);//优惠券面额
                        $resp['results']['n_tbk_item'][$k]['after_coupon_price'] = round($v['zk_final_price'] - get_coupon_price($gaoyonog['coupon_info']),2);//券后价
                    }
                    //过滤
                    if ($filter > 0){
                        if ($gaoyonog['max_commission_rate'] <= $filter)
                            unset($resp['results']['n_tbk_item'][$k]);
                    }
                }
               
            } */
            
        }
        //如果是空数组直接删除
        //if (isset($resp['results']['n_tbk_item']) && count($resp['results']['n_tbk_item'])==0){
            //unset($resp['results']);
        //}
        //dump($resp);die;
        //return $resp;
        return self::multi_gaoyong($resp,$filter);
    }
    /**
     * 废弃
     * curl 并发查高佣
     */
    private function multi_gaoyong($data,$filter=false)
    {
        if (!isset($data['results']['n_tbk_item'])){
            return $data;
        }
        debug('begin');//dump($data);
        
        $appkey = 'dHloVs8E';
        $appsecret = 'KKv3woax';
        //第一高佣查券
        $options = [];
        foreach ($data['results']['n_tbk_item'] as $k=>$v){
            $url = "http://tkapi.apptimes.cn/coupon?appkey={$appkey}&pid={$this->options['pid']}&good_id={$v['num_iid']}";
            $opt = [
                'url' => $url,
                'method' => 'GET',
            ];
            $options[] = $opt;
        }
        $mr  = MultiRequest::create();
        $re = $mr->setDefaults(['timeout'=>2])->addOptions($options)->sendAll();
        $list1 = [];
        foreach ($re as $response){
            $temp = json_decode($response->body,true);
            $temp['data']['time'] = $response->duration;
            $list1[$temp['data']['item_id']] = $temp['data'];
        }
        //dump($list1);
        //组装进原数据
        $options2 = [];
        foreach ($data['results']['n_tbk_item'] as $k=>$v){
            $data['results']['n_tbk_item'][$k] = array_merge($v,$list1[$v['num_iid']]);
            //组装第二步
            $url_str = substr($list1[$v['num_iid']]['coupon_click_url'],strrpos($list1[$v['num_iid']]['coupon_click_url'],'?')+1);
            parse_str($url_str,$arr);
            $e = $arr['e'];
            $e = urldecode($e);
            $timestamp = time();
            $sign = md5($appkey.$appsecret.$e.$timestamp);
            $e = urlencode($e);
            $check_url = "http://tkapi.apptimes.cn/coupon/info?appkey={$appkey}&e={$e}&t={$timestamp}&sign={$sign}";
            $opt = [
                'url' => $check_url,
                'method' => 'GET'
            ];
            $options2[] = $opt;
        }
        //判断高佣接口的二合一链接里面的券是否可用
        $mr2  = MultiRequest::create();
        $re2 = $mr2->setDefaults(['timeout'=>2])->addOptions($options2)->sendAll();
        $list2 = [];
        foreach ($re2 as $response){
            $temp = json_decode($response->body,true);
            $list2[$temp['data']['item']['itemId']]['clickUrl'] = 'https:'.$temp['data']['item']['clickUrl'];
            $list2[$temp['data']['item']['itemId']]['retStatus'] = $temp['data']['retStatus'];
           
        }
        //最后的再次组装
        foreach ($data['results']['n_tbk_item'] as $k=>$v){
            $data['results']['n_tbk_item'][$k] = array_merge($v,$list2[$v['num_iid']]);
            if (isset($v['coupon_info'])){
                $data['results']['n_tbk_item'][$k]['coupon_price'] = get_coupon_price($v['coupon_info']);//优惠券面额
                $data['results']['n_tbk_item'][$k]['after_coupon_price'] = round($v['zk_final_price'] - get_coupon_price($v['coupon_info']),2);//券后价
            }
            //过滤
            if ($filter > 0){
                if ($v['max_commission_rate'] <= $filter) unset($data['results']['n_tbk_item'][$k]);
            }
        }
        
        debug('end');
        trace('查询用时：'.debug('begin','end').'s');
        return $data;
        
    }
    /**
     * 高佣查询,单产品,使用中
     */
    public function gaoyong($num_iid){
        $appkey = $this->options['big_appkey'];
        $appsecret = $this->options['big_appsecret'];
        //缓存
        $cache_data = cache('tb_url_'.$this->options['pid'].'_'.$num_iid);
        if ($cache_data){
            return $cache_data;
        }
        //第一步查券
        $coupon_url = "http://tkapi.apptimes.cn/coupon?appkey={$appkey}&pid={$this->options['pid']}&good_id={$num_iid}";
        $conpou_info = json_decode(http_get($coupon_url),true);
        if ($conpou_info['errcode']!==0) {
            return false;
        }else { 
            //第二判断高佣接口的二合一链接里面的券是否可用
            $url_str = substr($conpou_info['data']['coupon_click_url'],strrpos($conpou_info['data']['coupon_click_url'],'?')+1);
            parse_str($url_str,$arr);
            $e = $arr['e'];
            $e = urldecode($e);
            //sign计算方法：拼接appkey,appsecret,e,t后的字符串进行md5加密32位小写，t时间戳10位.
            $timestamp = time();
            $sign = md5($appkey.$appsecret.$e.$timestamp);
            $e = urlencode($e);
            $check_url = "http://tkapi.apptimes.cn/coupon/info?appkey={$appkey}&e={$e}&t={$timestamp}&sign={$sign}";
            $re = http_get($check_url);
            $re = json_decode($re,true);
            //trace($re);
            if ($re['errcode']!==0){
                //临时解决方案
                $re_ = [
                    'retStatus' => 0,
                    'return_url' => $conpou_info['data']['coupon_click_url'],//返回第一步的
                    'item' => ['title'=>'接口异常，无法获取','picUrl'=>''],
                ];
                return array_merge($conpou_info['data'],$re_);
                //return false;
            }
            //上一步获取retStatus字段值，为0的话，说明券能用，直接用第一步获取的二合一链接（coupon_click_url值）发给用户或生成淘口令；
            //如果值不为0，说明券过期或被领完了，提取里面的clickUrl，这个值是单品高佣后的链接(记得链接前补全https)，发给用户或生成淘口令；
            $re_ = [
                'clickUrl' => 'https:'.$re['data']['item']['clickUrl'],
                'retStatus' => $re['data']['retStatus'],
                'return_url' => 'https:'.$re['data']['retStatus']==0 ? $conpou_info['data']['coupon_click_url'] : $re['data']['clickUrl'],
            ];
            $data = array_merge($conpou_info['data'],$re_,$re['data']);
            if ($re['errcode']==0){
                cache('tb_url_'.$this->options['pid'].'_'.$num_iid,$data);
            }
            return $data;
        }
    }
    /**
     * 12: 淘口令解析获取url和商品id
        api： http://tkapi.apptimes.cn/token/get-token?appkey=xxxxx&token=xxxxx
     */
    public function get_token($token)
    {
        $appkey = $this->options['big_appkey'];
        $appsecret = $this->options['big_appsecret'];
        $url = "http://tkapi.apptimes.cn/token/get-token?appkey={$appkey}&token=".$token;
        $re = json_decode(http_get($url),true);
        if ($re['errcode']==0){
            return $re['data']['item_id'];
        }
        return false;
    }
    
    /**
     * 淘宝客商品详情（简版）
     */
    public function info_get()
    {
        $c = new \TopClient();;
        $c->appkey = $this->options['appkey'];
        $c->secretKey = $this->options['appsecret'];
        $req = new \TbkItemInfoGetRequest();
        $req->setNumIids($this->options['num_iids']);
        $resp = $c->execute($req);
        return json_decode(json_encode($resp),true);
    }
    /**
     * 获取淘宝联盟选品库列表
     */
    public function favorites_get()
    {
        $c = new \TopClient();;
        $c->appkey = $this->options['appkey'];
        $c->secretKey = $this->options['appsecret'];
        $req = new \TbkUatmFavoritesGetRequest();
        $req->setPageNo("1");
        $req->setPageSize("20");
        $req->setFields("favorites_title,favorites_id,type");
        $req->setType("-1");
        $resp = $c->execute($req);
        return json_decode(json_encode($resp),true);
    }
    /**
     * 获取淘宝联盟选品库的宝贝信息
     */
    public function favorites_item_get()
    {
        $c = new \TopClient();;
        $c->appkey = $this->options['appkey'];
        $c->secretKey = $this->options['appsecret'];
        $req = new \TbkUatmFavoritesItemGetRequest();
        //链接形式：1：PC，2：无线，默认：１
        $platform = isset($this->options['platform']) ? $this->options['platform'] : "2";
        $req->setPlatform($platform);
        //页大小，默认20，1~100
        if (isset($this->options['page_size'])) $req->setPageSize($this->options['page_size']);
        //推广位id，需要在淘宝联盟后台创建；且属于appkey备案的媒体id（siteid），如何获取adzoneid，请参考，http://club.alimama.com/read-htm-tid-6333967.html?spm=0.0.0.0.msZnx5
        $req->setAdzoneId($this->options['adzoneid']);
        //自定义输入串，英文和数字组成，长度不能大于12个字符，区分不同的推广渠道
        if (isset($this->options['unid'])) $req->setUnid($this->options['unid']);
        //选品库的id
        $req->setFavoritesId($this->options['favorites_id']);
        //第几页，默认：1（当后台类目和查询词均不指定的时候，最多出10000个结果，即page_no*page_size不能超过200；当指定类目或关键词的时候，则最多出100个结果）
        if (isset($this->options['page_no'])) $req->setPageNo($this->options['page_no']);
        $req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,shop_title,zk_final_price_wap,event_start_time,event_end_time,tk_rate,status,type,click_url,coupon_click_url,coupon_end_time,coupon_info,coupon_start_time,coupon_total_count,coupon_remain_count");
        $resp = $c->execute($req);
        $resp = json_decode(json_encode($resp),true);
        //过滤
        $filter = isset($this->options['filter']) ?$this->options['filter'] : false ;
        $coupon_list = $resp['results']['uatm_tbk_item'];
        if ($coupon_list){
            if (!is_array($coupon_list[0])){
                $resp['results']['uatm_tbk_item'] = [];
                $resp['results']['uatm_tbk_item'][] = $coupon_list;
            }
            foreach ($resp['results']['uatm_tbk_item'] as $k=>$v){
                //删除失效的
                if (!isset($v['coupon_info'])){
                    //unset($resp['results']['tbk_coupon'][$k]);
                }else {
                    $resp['results']['uatm_tbk_item'][$k]['coupon_price'] = get_coupon_price($v['coupon_info']);//优惠券面额
                    $resp['results']['uatm_tbk_item'][$k]['after_coupon_price'] = round($v['zk_final_price_wap'] - get_coupon_price($v['coupon_info']),2);//券后价
                }
                
                //过滤
                if ($filter > 0){
                    if ($v['tk_rate'] <= $filter)
                        unset($resp['results']['uatm_tbk_item'][$k]);
                }
            }
        }
        
        return $resp;
    }
    /**
     * 正在使用
     * (通用物料搜索API（导购）)
     * 默认链接为转好的商业化链接，带券商品转成uland链接，不带券商品转成s.click链接，不需要再次转链。
     * 温馨提示：不建议推广者再次进行转链，会直接影响推荐结果
     * 在请求API参数中material_id设置为6707，其他参数保持不变，即可返回新搜索结果。
     */
    public function optional()
    {
        $c = new \TopClient();;
        $c->appkey = $this->options['appkey'];
        $c->secretKey = $this->options['appsecret'];
        $req = new \TbkDgMaterialOptionalRequest();
        //店铺dsr评分，筛选高于等于当前设置的店铺dsr评分的商品0-50000之间
        if (isset($this->options['start_dsr'])) $req->setStartDsr($this->options['start_dsr']);
        //页大小，默认20，1~100
        if (isset($this->options['page_size'])) $req->setPageSize($this->options['page_size']);
        //第几页，默认：1（当后台类目和查询词均不指定的时候，最多出10000个结果，即page_no*page_size不能超过200；当指定类目或关键词的时候，则最多出100个结果）
        if (isset($this->options['page_no'])) $req->setPageNo($this->options['page_no']);
        //链接形式：1：PC，2：无线，默认：１
        $platform = isset($this->options['platform']) ? $this->options['platform'] : "2";
        $req->setPlatform($platform);
        //淘客佣金比率上限，如：1234表示12.34%
        if (isset($this->options['start_tk_rate'])) $req->setStartTkRate($this->options['start_tk_rate']);
        //淘客佣金比率下限，如：1234表示12.34%
        if (isset($this->options['end_tk_rate'])) $req->setEndTkRate($this->options['end_tk_rate']);
        //折扣价范围下限，单位：元
        if (isset($this->options['start_price'])) $req->setStartPrice($this->options['start_price']);
        //折扣价范围上限，单位：元
        if (isset($this->options['end_price'])) $req->setEndPrice($this->options['end_price']);
        //	排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi），价格（price
        if (isset($this->options['sort']))  $req->setSort($this->options['sort']);
        //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
        if (isset($this->options['is_tmall'])) $req->setIsTmall($this->options['is_tmall']);
        //是否海外商品，设置为true表示该商品是属于海外商品，设置为false或不设置表示不判断这个属性
        if (isset($this->options['is_overseas'])) $req->setIsOverseas($this->options['is_overseas']);
        //查询词
        if (isset($this->options['q'])) $req->setQ($this->options['q']);
        //后台类目ID，用,分割，最大10个，该ID可以通过taobao.itemcats.get接口获取到
        if (isset($this->options['cat'])) $req->setCat($this->options['cat']);
        //所在地
        if (isset($this->options['itemloc'])) $req->setItemloc($this->options['itemloc']);
        //是否有优惠券，设置为true表示该商品有优惠券，设置为false或不设置表示不判断这个属性
        if (isset($this->options['has_coupon'])) $req->setHasCoupon($this->options['has_coupon']);
        //新加功能
        //官方的物料Id(详细物料id见：https://tbk.bbs.taobao.com/detail.html?appId=45301&postId=8576096)，不传时默认为2836
        //在请求API参数中material_id设置为6707，其他参数保持不变，即可返回新搜索结果。
        $material_id = isset($this->options['material_id']) ? $this->options['material_id'] : '6707';
        $req->setMaterialId($material_id);
        
        //mm_xxx_xxx_xxx的第三位  必须
        $req->setAdzoneId($this->options['adzoneid']);
        $resp = $c->execute($req);
        $resp = json_decode(json_encode($resp),true);
        if ($resp['total_results']>0){
            if (!is_array($resp['result_list']['map_data'][0])){
                $temp_n_tbk_item = $resp['result_list']['map_data'];
                $resp['result_list']['map_data'] = [];
                $resp['result_list']['map_data'][] = $temp_n_tbk_item;
            }
             
        }
        return $resp;
    }
    /**
     * 生成淘口令
     */
    public function create_tkl()
    {
        $cache_data = cache('tkl_'.$this->options['text'].'_'.$this->options['url'].'_'.$this->options['logo']??'');
        if ($cache_data){
            return $cache_data;
        }
        $c = new \TopClient();;
        $c->appkey = $this->options['appkey'];
        $c->secretKey = $this->options['appsecret'];
        $req = new \TbkTpwdCreateRequest();
        //$req->setUserId("123");
        $req->setText($this->options['text']);
        $req->setUrl($this->options['url']);
        //口令弹框logoURL
        if (isset($this->options['logo'])) $req->setLogo($this->options['logo']);
        //$req->setExt("{}");
        $resp = $c->execute($req);
        $resp = json_decode(json_encode($resp),true);
        $tkl = $resp['data']['model'] ?? '';
        if ($tkl){
            cache('tkl_'.$this->options['text'].'_'.$this->options['url'].'_'.$this->options['logo']??'',$tkl);
        }
        return $tkl;
    }
    /**
     * 发圈-好单库
     */
    public function faquan($min_id=1)
    {
        $appkey = 'duoduojie';
        $url = "http://v2.api.haodanku.com/selected_item/apikey/{$appkey}/min_id/{$min_id}";
        //缓存
        $cache_data = cache($url);
        if ($cache_data){
            return $cache_data;
        }
        $re = http_get($url);
        $re = json_decode($re,true);
        if ($re['code']==1){
            foreach ($re['data'] as $k=>$v){
                $re['data'][$k]['add_time'] = date('Y-m-d',$v['add_time']);
                $re['data'][$k]['show_time'] = date('Y-m-d',$v['show_time']);
                $re['data'][$k]['advise_time'] = date('Y-m-d',$v['advise_time']);
                $re['data'][$k]['content'] = preg_replace('/\$(.*)\$/', '', $v['content']);
            }
            cache($url,$re,3600);
            return $re;
        }
        return false;
    }
    /**
     * 导订单
     * http://tkapi.apptimes.cn/order?appkey=xxxx&appsecret=xxxx&&start_time=2018-12-38 10:00:00&span=600
     * start_time往后600秒之内的订单 span最大1200秒(20分钟).(查询一天之内需轮询72次.)接口数据有部分字段收货后才有值.(范例末尾.)
     *http://tkapi.apptimes.cn/order?appkey=&appsecret=&fields=&start_time=&span=&page_no=&page_size=&tk_status=&order_query_type=
     * 其它参数请参考：http://open.taobao.com/api.htm?docId=38078&docType=2&scopeId=14814
     * 不传start_time 则为查询多少秒前的订单
     */
    public function import_order($span,$start_time='')
    {
        $appkey = $this->options['big_appkey'];
        $appsecret = $this->options['big_appsecret'];
        $param = [
            'order_query_type' => $this->options['order_query_type'] ?? 'create_time',
            //'fields' => 'tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,relation_id,tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,special_id,click_time',
        ];
        if (isset($this->options['page_no'])) $param['page_no'] = $this->options['page_no'];
        if (isset($this->options['page_size'])) {
            $param['page_size'] = $this->options['page_size'];
        }else {
            $param['page_size'] = 100;
        }
        if (empty($start_time)){
            $start_time = date('Y-m-d H:i:s',time()-$span);
        }
        $url = "http://tkapi.apptimes.cn/order?appkey={$appkey}&appsecret={$appsecret}&&start_time={$start_time}&span={$span}&";
        $re = http_get($url.http_build_query($param));
        $re = json_decode($re,true,512,JSON_BIGINT_AS_STRING);
        return $re;
    }
    /**
     * 淘宝客商品关联推荐查询
     */
    public function item_recommend()
    {
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}